<template>
  <el-container style="flex-direction: column;">
    <!-- 引入头部 -->
    <OwnerHeader :userInfo="userInfo" />

    <!-- 社区活动总标题 -->
    <div class="section title-section">
      <h2>社区活动</h2>
    </div>

    <!-- 查询区域 -->
    <div class="section search-section">
      <el-row :gutter="20">
        <el-input v-model="searchName" placeholder="按活动名称查询" style="width: 200px; margin-left: 50px" clearable />
        <el-select v-model="searchStatus" placeholder="请选择状态" style="width: 150px; margin-left: 50px" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="准备中" value="1"></el-option>
          <el-option label="报名中" value="2"></el-option>
          <el-option label="活动中" value="3"></el-option>
          <el-option label="活动结束" value="4"></el-option>
        </el-select>
        <el-date-picker v-model="searchRegistrationDate" type="datetime" placeholder="报名时间"
          value-format="yyyy-MM-dd hh:mm:ss" style="width: 200px; margin-left: 50px" />
        <el-date-picker v-model="searchActivityDate" type="datetime" placeholder="活动时间"
          value-format="yyyy-MM-dd hh:mm:ss" style="width: 200px; margin-left: 50px" />
        <el-button type="primary" @click="handleSearch" style="margin-left: 50px">查询</el-button>
      </el-row>
    </div>

    <!-- 活动列表 -->
    <div class="section activities-section">
      <el-row :gutter="20">
        <el-col v-for="activity in activities" :key="activity.id" :span="8">
          <el-card class="activity-card">
            <!-- 添加已报名标签 -->
            <div v-if="registerActivities.includes(activity.id)" class="registered-label">
              已报名
            </div>
            <div class="activity-image">
              <img :src="activity.imageUrl" alt="活动图片" @error="handleImageError" />
            </div>
            <div class="activity-header">
              <h3>{{ activity.activityName }}</h3>
              <div class="activity-time">
                <p><strong>活动时间：</strong>{{ activity.activityStart }} - {{ activity.activityDeadline }}</p>
                <p><strong>报名时间：</strong>{{ activity.registrationStart }} - {{ activity.registrationDeadline }}</p>
              </div>
            </div>
            <div class="activity-content">
              <p><strong>地点：</strong>{{ activity.location }}</p>
              <p><strong>最大人数：</strong>{{ activity.maxParticipants === 0 ? '无限制' : activity.maxParticipants }}</p>
              <p><strong>已报名人数：</strong>{{ activity.currentParticipants }}</p>
              <p>活动描述： {{ activity.description }}</p>
            </div>
            <div class="activity-footer">
              <el-button v-if="activity.status === 4" type="info" :disabled="true">
                活动结束
              </el-button>

              <el-button v-if="activity.status === 3" :disabled="true"
                style="background-color: #e6f7ff; border-color: #99ccff;">
                活动中
              </el-button>

              <el-button v-if="activity.status === 2"
                :type="registerActivities.includes(activity.id) ? 'success' : 'primary'"
                @click="handleSignUp(activity)">
                {{ registerActivities.includes(activity.id) ? '已报名' : '我要报名' }}
              </el-button>
              <el-button v-if="activity.status === 1" :disabled="true"
                style="background-color: #e6f7ff; border-color: #99ccff; color: black;">
                准备中
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 报名弹窗 -->
    <el-dialog :title="registerActivities.includes(currentActivity.id) ? '取消报名活动' : '确认报名活动'"
      :visible.sync="isSignUpDialogVisible" width="30%">
      <h2>{{ currentActivity.activityName }}</h2>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isSignUpDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSignUp">确认</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import OwnerHeader from '@/components/owner_components/OwnerHeader.vue';
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
  name: 'OwnerActivityView',
  components: {
    OwnerHeader,
  },
  data() {
    return {
      userInfo: {},
      isSignUpDialogVisible: false, // 报名弹窗是否显示
      currentActivity: {}, // 当前报名的活动

      searchName: '', // 按名称查询
      searchStatus: '', //状态查询
      searchRegistrationDate: '', // 报名时间查询
      searchActivityDate: '', // 活动时间查询

      activities: [], // 活动列表
      registerActivities: [], // 已报名的活动 ID 列表
    };
  },
  mounted() {
    this.userInfo = parseJwt(localStorage.getItem('token')).payload;
    this.handleSearch();
    this.getRegisterActivities(); // 获取已报名的活动
  },
  methods: {
    // 获取已报名的活动
    getRegisterActivities() {
      service.get(`/api/user/activity/getRegisterActivities/${this.userInfo.id}`)
        .then(result => {
          result = result.data;
          if (result.code == 1) {
            this.registerActivities = result.data;
          }
        });
    },
    // 点击报名按钮
    handleSignUp(activity) {
      this.currentActivity = activity;
      this.isSignUpDialogVisible = true;
    },
    // 提交报名信息
    submitSignUp() {
      if (this.registerActivities.includes(this.currentActivity.id)) {
        service.get(`/api/user/activity/deleteRegisterActivity/${this.userInfo.id}/${this.currentActivity.id}`)
          .then(result => {
            result = result.data;
            if (result.code == 1) {
              this.$message.success('取消报名成功');
              this.isSignUpDialogVisible = false;
              this.handleSearch(); // 重新查询活动列表
              this.getRegisterActivities(); // 重新获取已报名活动
            }
          });
      } else {
        service.get(`/api/user/activity/addRegisterActivity/${this.userInfo.id}/${this.currentActivity.id}`)
          .then(result => {
            result = result.data;
            if (result.code == 1) {
              this.$message.success('报名成功');
              this.isSignUpDialogVisible = false;
              this.handleSearch(); // 重新查询活动列表
              this.getRegisterActivities(); // 重新获取已报名活动
            }
          });
      }
    },
    // 查询活动
    handleSearch() {
      service.get('/api/user/activity/getActivityList', {
        params: {
          activityName: this.searchName,
          status: this.searchStatus,
          registrationDate: this.searchRegistrationDate,
          activityDate: this.searchActivityDate,
        }
      }).then(result => {
        result = result.data;
        if (result.code == 1) {
          this.activities = result.data.map(activity => ({
            ...activity,
            maxParticipants: activity.maxParticipants || 0, // 默认最大人数为 0（无限制）
            registeredParticipants: activity.registeredParticipants || 0, // 默认已报名人数为 0
          }));
        }
      });
    },
    // 图片加载失败处理
    handleImageError(event) {
      event.target.src = 'https://via.placeholder.com/400x200'; // 默认图片
    },
  },
};
</script>

<style scoped>
.section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.title-section {
  background-color: #ffffff;
  text-align: center;
}

.title-section h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.search-section {
  background-color: #f5f7fa;
}

.activities-section {
  background-color: #ffffff;
}

/* 添加已报名标签样式 */
.registered-label {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #67c23a;
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 1;
}

.activity-card {
  position: relative;
  margin-bottom: 20px;
}

.activity-image img {
  width: 50%;
  height: auto;
  border-radius: 4px;
  margin-top: 10px;
}

.activity-header {
  margin-bottom: 10px;
}

.activity-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.activity-time {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.activity-content {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.activity-content p {
  margin: 5px 0;
}

.activity-footer {
  text-align: right;
}
</style>